var mapa_interface={
	hooks:{
		iniciado:[],
		markAdded:[]
	},
	boundsChanged_timeOut:null,
	init:function(){
		this.container=document.getElementById(this.params.key);
		if(this.container){
			this.mapa=new google.maps.Map(this.container,this.params);
			this.mapa.key=this.params.key;
		}
		for(var i=0;i<mapa_interface.hooks.iniciado.length;i++){
			mapa_interface.hooks.iniciado[i](this);
		}
	},
	boundsChanged:function(){
		if(mapa_interface.boundsChanged_timeOut){
			clearTimeout(mapa_interface.boundsChanged_timeOut);
		}
		mapa_interface.boundsChanged_timeOut=setTimeout("mapasDDBB[0].loadMarks()",1000);
	},
	loadMarks:function(){
		var script=document.createElement("script");
		var bounds=this.mapa.getBounds();
		var ne=bounds.getNorthEast();
		var sw=bounds.getSouthWest();
		script.src="api/markers/"+ne.lat()+":"+ne.lng()+":"+sw.lat()+":"+sw.lng()+"?callback=mapa_interface.marksproxy&idcallback="+this.key;
		script.type="text/javascript";
		document.getElementsByTagName("head")[0].appendChild(script);
		//alert(script.src);
	},
	marksproxy:function(results,key){
		for(var i=0;i<mapasDDBB.length;i++){
			if(mapasDDBB[i].key==key){
				mapasDDBB[i].clean();
				for(var j=0;j<results.results.length;j++){
					mapasDDBB[i].addMarker(results.results[j]);
				}
				mapasDDBB[i].updateParrilla();
			}
		}
	},
	createMarker:function(data){
		var m= new google.maps.Marker({
		      position: new google.maps.LatLng(data.lat,data.lon), 
		      title:data.titulo
		  });
		m.infowindow=new google.maps.InfoWindow({
								    content: ""
								});
		
		google.maps.event.addListener(m,"click",function(){
			this.showInfoWindow();
		});
		m.comollego=mapa_marker_c.comollego;
		m.hideInfo=mapa_marker_c.hideInfo;
		m.medirdistancia=mapa_marker_c.medirdistancia;
		m.addToRoute=mapa_marker_c.addToRoute;
		m.controller=this;
		m.datos=data;
		m.showInfoWindow=mapa_marker_c.showInfoWindow;
		return m;
	},
	addMarker:function(marcador){
		var m=this.createMarker(marcador);
		m.setMap(this.mapa);
		this.marcadores.push(m);
		m.payID=this.marcadores.length-1;
		for(var i=0;i<mapa_interface.hooks.markAdded.length;i++){
			mapa_interface.hooks.markAdded[i](this,m);
		}

	},
	updateParrilla:function(){
		if(this.params.parrilla){
			var container=$("#"+this.params.parrilla);
			container.empty();
		}
	},
	clean:function(){
		var i;
		while(i=this.marcadores.pop()){
			i.hideInfo();
			i.setMap(null);
		}
	},
	showUserPos:function(dondeestoy,options,callback){
		if(!options){
			options={
		      position: new google.maps.LatLng(0,0), 
		      map: this.mapa, 
		      title:"imhere",
		      draggable:true
		  }
		}
		if(this.userPos){
			this.userPos.setMap(null);
		}
		this.userPos= new google.maps.Marker(options);
		dondeestoy.centerGoogleMapsMarker(this.userPos,callback);
	},
	updateDistancia:function(result){
		for(var i=0;i<this.marcadores.length;i++){
			if(this.marcadores[i].infowin){
				this.marcadores[i].infowin.showDistance(result);
			}
		}
	},
	showRuta:function(posiciones){
			if(!this.directionsService){
				this.directionsService= new google.maps.DirectionsService();
			}
			if(!this.directionsDisplay){
				this.directionsDisplay=new google.maps.DirectionsRenderer();
				this.directionsDisplay.setMap(this.mapa);
			}
			
			var request={
				origin:posiciones[0].getPosition(),
				destination:posiciones[posiciones.length-1].getPosition(),
				travelMode:google.maps.TravelMode.DRIVING,
				waypoints:[]
			}
			
			for(var i=1;i<posiciones.length-1;i++){
				request.waypoints.push({location:posiciones[i].getPosition(),stopover:true});
			}
			
			this.directionsService.route(request, function(result, status) {
					    if (status == google.maps.DistanceMatrixElementStatus.OK) {
					     	mapasDDBB[0].directionsDisplay.setDirections(result);
					    }
  });
			
	}
}
var mapa_marker_c={
	addToRoute:function(){
			for(var i=0;i<rutas_c.ddbb.length;i++){
				rutas_c.ddbb[i].agregar(this);
			}
	},
	comollego:function(){
		if(this.controller.userPos){
			if(!this.controller.directionsService){
				this.controller.directionsService= new google.maps.DirectionsService();
			}
			if(!this.controller.directionsDisplay){
				this.controller.directionsDisplay=new google.maps.DirectionsRenderer();
				this.controller.directionsDisplay.setMap(this.getMap());
			}
			var request={
				origin:this.controller.userPos.getPosition(),
				destination:this.getPosition(),
				travelMode:google.maps.TravelMode.DRIVING
			}
			this.controller.directionsService.route(request, function(result, status) {
					    if (status == google.maps.DirectionsStatus.OK) {
					    	
					     mapasDDBB[0].directionsDisplay.setDirections(result);
					    }
  });
		}
	},
	showInfoWindow:function(){
			//this.infowindow.setContent("<input type='button' value='como Llegar' onclick='javascript:mapasDDBB[0].marcadores["+this.payID+"].comollego()'>");
			//this.infowindow.open(this.getMap(),this);
			if(this.infowin){
				this.infowin.setMap(null);
			}
			this.infowin=new mapa_info_h(this);
	},
	medirdistancia:function(){
		if(this.controller.userPos){
			if(!this.controller.DistanceMatrixService){
				this.controller.DistanceMatrixService= new google.maps.DistanceMatrixService();
			}
			var request={
				origins:[this.controller.userPos.getPosition()],
				destinations:[this.getPosition()],
				travelMode:google.maps.TravelMode.DRIVING
			}
			this.controller.DistanceMatrixService.getDistanceMatrix(request, function(result, status) {
					    if (status == google.maps.DistanceMatrixElementStatus.OK) {
					     	mapasDDBB[0].updateDistancia(result, status);
					    }
  });
		}
		else {
			mapasDDBB[0].showUserPos(dondeestoy,null,"mapasDDBB[0].marcadores["+this.payID+"].medirdistancia()");
		}
	},
	hideInfo:function(){
			if(this.infowin){
				this.infowin.setMap(null);
				this.infowin=null;
			}
	}
}

var mapa_info_h=function(marcador){
	this.marcador=marcador;
	this.onAdd=mapa_info_c.onAdd;
	this.draw=mapa_info_c.draw;
	this.onRemove=mapa_info_c.onRemove;
	this.showDistance=mapa_info_c.showDistance;
	this.showData=mapa_info_c.showData;
	this.setMap(marcador.getMap());
}
var mapa_info_c={
	showDistance:function(result){
		var div=$(this.div_).find(".wrap").get()[0];
		$(div).empty();
		div.className="distancia";
		
		var origen=document.createElement("div");
		origen.className="origen";
		var origen_label=document.createElement("label");
		origen_label.className="origen_label";
		$(origen_label).append("Origen");
		var origen_input=document.createElement("div");
		origen_input.className="origen_input data";
		$(origen_input).append(result.originAddresses[0]);
		
		var destino=document.createElement("div");
		destino.className="destino";
		var destino_label=document.createElement("label");
		destino_label.className="destino_label";
		$(destino_label).append("Destino");
		var destino_input=document.createElement("div");
		destino_input.className="destino_input data";
		$(destino_input).append(this.marcador.datos.titulo);
		
		var distancia=document.createElement("div");
		distancia.className="distancia";
		var distancia_label=document.createElement("label");
		distancia_label.className="distancia_label";
		$(distancia_label).append("Distancia");
		var distancia_input=document.createElement("div");
		distancia_input.className="distancia_input data";
		$(distancia_input).append(result.rows[0].elements[0].distance.text);
		
		var tiempo=document.createElement("div");
		tiempo.className="tiempo";
		var tiempo_label=document.createElement("label");
		tiempo_label.className="tiempo_label";
		$(tiempo_label).append("Tiempo");
		var tiempo_input=document.createElement("div");
		tiempo_input.className="tiempo_input data";
		$(tiempo_input).append(result.rows[0].elements[0].duration.text);

		
		$(origen).append(origen_label);
		$(origen).append(origen_input);
		$(destino).append(destino_label);
		$(destino).append(destino_input);
		$(distancia).append(distancia_label);
		$(distancia).append(distancia_input);
		$(tiempo).append(tiempo_label);
		$(tiempo).append(tiempo_input);
		
		$(div).append(origen);
		$(div).append(destino);
		$(div).append(distancia);
		$(div).append(tiempo);
		
	},
	showData:function(){
		
		var div=$(this.div_).find(".wrap").get()[0];
		$(div).empty();
		var a=document.createElement("a");
		a.href=this.marcador.datos.link;
		var imagen=document.createElement("img");
		imagen.src=this.marcador.datos.thumbnail;
		imagen.className="thumbnail";
		
		var titulo=document.createElement("div");
		titulo.className="titulo";
		titulo.appendChild(document.createTextNode(this.marcador.datos.titulo));
		
		a.appendChild(imagen);
		div.appendChild(a);
		div.appendChild(titulo);
		
	},
	onAdd:function(){
		var div=document.createElement("div");
		div.className="pay_infowindow";
		  div.style.border = "none";
		  div.style.borderWidth = "0px";
		  div.style.position = "absolute";
		  div.style.background="url('img/globo.png') 0 0 no-repeat";
		  
		var wrap=document.createElement("div");
		wrap.className="wrap";
		
		
		var controles=document.createElement("div");
		controles.className="controles";
		
		var distancia=document.createElement("div");
		distancia.className="distancia_button";
		distancia.appendChild(document.createTextNode("distancia"));
		distancia.title=this.marcador.payID;
		
		var agregar=document.createElement("div");
		agregar.className="agregar";
		agregar.appendChild(document.createTextNode("agregar"));
		agregar.title=this.marcador.payID;
		
		var datos=document.createElement("div");
		datos.className="datos";
		datos.appendChild(document.createTextNode("datos"));
		datos.title=this.marcador.payID;
		
		$(distancia).click(function(){mapasDDBB[0].marcadores[this.title*1].medirdistancia()});
		$(datos).click(function(){mapasDDBB[0].marcadores[this.title*1].showInfoWindow()});
		$(agregar).click(function(){mapasDDBB[0].marcadores[this.title*1].addToRoute();});
		
		
		controles.appendChild(distancia);
		controles.appendChild(datos);
		controles.appendChild(agregar);
		div.appendChild(controles);
		div.appendChild(wrap);
		
		this.div_ = div;
		this.showData();
	},
	draw:function(){
		var div=this.div_;
		var panes = this.getPanes();
		//alert(panes.getKeys());
 		panes.overlayMouseTarget.appendChild(div);
		var overlayProjection = this.getProjection();
		var sw = overlayProjection.fromLatLngToDivPixel(this.marcador.getPosition());
		div.style.left=sw.x+"px";
		div.style.top=(sw.y-200)+"px";
		div.style.width="400px";
		div.style.height="200px";
	},
	onRemove:function(){
		this.div_.parentNode.removeChild(this.div_);
  		this.div_ = null;
	}
	
}
mapa_info_h.prototype= new google.maps.OverlayView();

var mapa_class=function(params){
	this.boundsChangedTimeout=100000;
	this.key=params.key;
	this.params=params;
	this.marcadores=[];
	this.boundsChangedCallbacks=[];
	this.init=mapa_interface.init;
	this.showRuta=mapa_interface.showRuta;
	this.loadMarks=mapa_interface.loadMarks;
	this.createMarker=mapa_interface.createMarker;
	this.addMarker=mapa_interface.addMarker;
	this.updateParrilla=mapa_interface.updateParrilla;
	this.clean=mapa_interface.clean;
	this.directionsService= new google.maps.DirectionsService();
	this.updateDistancia=mapa_interface.updateDistancia;
	this.showUserPos=mapa_interface.showUserPos;
	if(typeof(this.params.center)=="string"){
		this.params.center=eval("("+this.params.center+")");
		}
	if(typeof(this.params.mapTypeId)=="string"){
		this.params.mapTypeId=eval("("+this.params.mapTypeId+")");
		}
	if(typeof(this.params.zoom)=="string"){
		this.params.zoom=this.params.zoom*1;
		}
	if(typeof(this.params.mapTypeControl)=="string"){
		this.params.mapTypeControl=eval("("+this.params.mapTypeControl+")");
		}
	if(typeof(this.params.streetViewControl)=="string"){
		this.params.streetViewControl=eval("("+this.params.streetViewControl+")");
		}
	if(typeof(this.params.zoomControl)=="string"){
		this.params.zoomControl=eval("("+this.params.zoomControl+")");
		}
		
	if(this.params.iniciar==1)
	{
		this.init();
	}
	if(this.mapa&&this.params.marcadores==1){
		google.maps.event.addListener(this.mapa,"bounds_changed",mapa_interface.boundsChanged)
	}
}

var mapasDDBB=[];
